//
//  ApiMoyaRequest.swift
//  MySwiftObject
//
//  Created by anscen on 2022/1/10.
//  Copyright © 2022 wangws1990. All rights reserved.
//

import UIKit
import Moya
import RxSwift
import RxCocoa
fileprivate let moyaProvider = MoyaProvider<ApiMoya>(requestClosure:timeOut)
//MARK:网络请求超时
fileprivate let timeOut = { (endpoint: Endpoint, done: @escaping MoyaProvider<ApiMoya>.RequestResultClosure) in
    guard var request = try? endpoint.urlRequest() else { return }
    request.timeoutInterval = TimeInterval(moya.timeOut)
    done(.success(request))
}
extension ApiMoya{
    //MARK:取消所有请求
    public static func cancelAllRequests(){
        moyaProvider.session.session.getAllTasks { listData in
            listData.forEach { task in
                debugPrint(task.taskIdentifier)
            }
        }
        moyaProvider.session.cancelAllRequests()
    }
//    //MARK:取消单个请求
//    public static func cancle(_ target :ApiMoya){
//        moyaProvider.cancelCompletion({ result in
//
//        }, target: target)
//    }
    //MARK:网络请求类目前只封装而成以后看需要是否需要封装多层目前主要三个
    //MARK:1、分页返回总页数，有分页可以使用该接口
    public static func request<T :HandyJSON>(target:ApiMoya,
                                              model:T.Type,
                                            sucesss:@escaping (_ object :[T?]  ) ->(),
                                            failure:@escaping ((_ error : String)->())){
        baserRequest(target: target, sucesss: { json, object, message in
            guard let model = ApiPageModel.deserialize(from:json.rawString()) else {
                return failure("解析失败")
            }
            var listData :[T] = []
            model.list.forEach { objc in
                let js = JSON(objc)
                if let data = T.deserialize(from: js.rawString()){
                    listData.append(data)
                }
            }
            sucesss(listData)
        }, failure: failure)
    }
    //MARK:2、普通网络请求使用该接口
    public static func request(target: ApiMoya,
                               sucesss:@escaping (_ json : JSON) ->(),
                               failure:@escaping ((_ error : String)->())){
        baserRequest(target: target, sucesss: { json, object, message in
            sucesss(json)
        }, failure: failure)
    }
    //MARK:3、是否需要提示信息
    public static func request(target: ApiMoya,
                               sucesss:@escaping (_ json :JSON,_ message :String) ->(),
                               failure:@escaping ((_ error :String)->())){
        baserRequest(target: target ,sucesss: { (json, dic,message) in
            sucesss(json,message)
        }, failure: failure)
    }
    //MARK:网络请求基类
    private static func baserRequest(target: ApiMoya,
                                    sucesss:@escaping (_ json : JSON,
                                                       _ object : Any,
                                                       _ message :String) ->(),
                                    failure:@escaping ((_ error : String) ->())){
        moyaProvider.request(target, callbackQueue: DispatchQueue.main, progress: nil) { (result) in
            switch result{
            case let .success(respond):do {
                if respond.statusCode != 200 {
                    log(target, show: true)
                    return failure("statusCode code == \(respond.statusCode)")
                }
                let json = JSON(respond.data)
                switch target {
                case .mandetail,.manchapter:
                    let js = json["data"]["returnData"]
                    sucesss(js,respond.data,"")
                    break
                default:
                    sucesss(json,respond.data,"")
                    break
                }
            };break
            case let .failure(error):
                if error.errorDescription != "Request explicitly cancelled."{
                    log(target, show: true)
                    failure(error.errorDescription ?? "")
                }
                break
            }
        }
    }
    //MARK:打印输出log
    fileprivate static func log(_ target : ApiMoya,show: @autoclosure() ->Bool){
        if show() {
            debugPrint("==============================")
            debugPrint(target.baseURL)
            debugPrint(target.path)
            debugPrint(target.task)
            debugPrint("==============================")
        }
    }
}
